import React from 'react';
import { DragDropContext, Draggable, Droppable } from 'react-beautiful-dnd';
import { DeleteOutlined, DownOutlined, EditOutlined, RightOutlined } from '@ant-design/icons';
import { Button, Divider, Form, Input, Popconfirm, Typography } from 'antd';
import { useRecoilState, useResetRecoilState } from 'recoil';
import CommonEdit from '@/components/CommonEdit';
import {
  advantageInfo,
  workInfo,
  baseInfo,
  educationInfo,
  objectInfo,
  order,
  shineBlogInfo,
} from '@/stores/store-resume';

const layout = {
  labelCol: {
    span: 8,
  },
  wrapperCol: {
    span: 16,
  },
};

const { Title } = Typography;

const ResumeCreate = () => {
  // 顺序
  const [storeOrder, setStoreOrder] = useRecoilState(order);
  const resetOrder = useResetRecoilState(order);

  // 基础信息
  const [storeBaseInfo, setStoreBaseInfo] = useRecoilState(baseInfo);
  const resetBaseInfo = useResetRecoilState(baseInfo);

  // 教育经历
  const [storeEducationInfo, setStoreEducationInfo] = useRecoilState(educationInfo);
  const resetEducationInfo = useResetRecoilState(educationInfo);

  // 教育经历
  const [storeShineBlogInfo, setShineBlogInfo] = useRecoilState(shineBlogInfo);
  const resetShineBlogInfo = useResetRecoilState(shineBlogInfo);

  // 个人优势
  const [storeAdvantageInfo, setStoreAdvantageInfo] = useRecoilState(advantageInfo);
  const resetAdvantageInfo = useResetRecoilState(advantageInfo);

  // 工作经历
  const [storeWorkInfo, setStoreWorkInfo] = useRecoilState(workInfo);
  const resetWorkInfo = useResetRecoilState(workInfo);

  // 项目经历
  const [storeObjectInfo, setStoreObjectInfo] = useRecoilState(objectInfo);
  const resetObjectInfo = useResetRecoilState(objectInfo);

  // 初始化
  const retAllData = () => {
    resetOrder();
    resetBaseInfo();
    resetEducationInfo();
    resetShineBlogInfo();
    resetAdvantageInfo();
    resetWorkInfo();
    resetObjectInfo();
  };

  const storeItem = (key, values) => {
    return values.find((item) => item.field === key);
  };

  const storeItemById = (key, values) => {
    return values.find((item) => item.id === key);
  };

  // 修改工作经历
  const changeWorkInfo = (value, item, x) => {
    const faVal = storeItemById(item.id, storeWorkInfo);
    const newChildVal = { ...storeItem(x.field, faVal.child), value };
    const newFaVal = faVal.child.map((i) => {
      if (x.field === i.field) {
        return newChildVal;
      } else {
        return i;
      }
    });

    setStoreWorkInfo((val) => {
      return val.map((i) => {
        if (item.id === i.id) {
          return {
            id: i.id,
            child: newFaVal,
          };
        } else {
          return i;
        }
      });
    });
  };

  // 修改项目经历
  const changeObjectInfo = (value, item, x) => {
    const faVal = storeItemById(item.id, storeObjectInfo);
    const newChildVal = { ...storeItem(x.field, faVal.child), value };
    const newFaVal = faVal.child.map((i) => {
      if (x.field === i.field) {
        return newChildVal;
      } else {
        return i;
      }
    });

    setStoreObjectInfo((val) => {
      return val.map((i) => {
        if (item.id === i.id) {
          return {
            id: i.id,
            child: newFaVal,
          };
        } else {
          return i;
        }
      });
    });
  };

  // a little function to help us with reordering the result
  const reorder = (list, startIndex, endIndex) => {
    const result = Array.from(list);
    const [removed] = result.splice(startIndex, 1);

    result.splice(endIndex, 0, removed);

    return result;
  };

  const onDragEnd = (result) => {
    // dropped outside the list
    if (!result.destination) {
      return;
    }

    const val = reorder(storeOrder, result.source.index, result.destination.index);

    setStoreOrder(val);
  };

  const allValues = [
    {
      key: '1',
      label: '基本信息',
      children: (
        <>
          <div className="grid grid-cols-2">
            {storeBaseInfo.map((child) => (
              <Form.Item key={child.field} label={child.label}>
                <Input
                  value={child.value}
                  placeholder={`请输入${child.label}`}
                  onChange={(e) => {
                    const newVal = { ...storeItem(child.field, storeBaseInfo), value: e.target.value };

                    setStoreBaseInfo((e) => {
                      return e.map((item) => {
                        if (item.field === child.field) {
                          return newVal;
                        } else {
                          return item;
                        }
                      });
                    });
                  }}
                />
              </Form.Item>
            ))}
          </div>
        </>
      ),
    },
    {
      key: '2',
      label: '教育经历',
      children: (
        <>
          <div className="grid grid-cols-2">
            {storeEducationInfo.map((child) => (
              <Form.Item key={child.field} label={child.label}>
                <Input
                  placeholder={`请输入${child.label}`}
                  value={child.value}
                  onChange={(e) => {
                    const newVal = { ...storeItem(child.field, storeEducationInfo), value: e.target.value };

                    setStoreEducationInfo((e) => {
                      return e.map((item) => {
                        if (item.field === child.field) {
                          return newVal;
                        } else {
                          return item;
                        }
                      });
                    });
                  }}
                />
              </Form.Item>
            ))}
          </div>
        </>
      ),
    },
    {
      key: '3',
      label: '社区博客',
      children: (
        <Form.Item wrapperCol={{ span: 24 }}>
          <div className="pl-48px">
            <CommonEdit
              keys={['insertLink']}
              html={storeShineBlogInfo.value}
              setHtml={(e) => {
                setShineBlogInfo(() => {
                  return {
                    ...storeShineBlogInfo,
                    value: e,
                  };
                });
              }}
            />
          </div>
        </Form.Item>
      ),
    },
    {
      key: '4',
      label: '个人优势',
      children: (
        <Form.Item key={storeAdvantageInfo.field} name={storeAdvantageInfo.field} wrapperCol={{ span: 24 }}>
          <div className="pl-48px">
            <CommonEdit
              html={storeAdvantageInfo.value}
              setHtml={(e) => {
                setStoreAdvantageInfo(() => {
                  return {
                    ...storeAdvantageInfo,
                    value: e,
                  };
                });
              }}
            />
          </div>
        </Form.Item>
      ),
    },
    {
      key: '5',
      label: '工作经历',
      children: (
        <>
          {storeWorkInfo.map((item) => (
            <div key={item.id}>
              <div className="grid grid-cols-2">
                {item.child.map((x) => {
                  if (x.label === '工作概述') return;

                  return (
                    <Form.Item key={x.field} label={x.label}>
                      <Input
                        placeholder={`请输入${x.label}`}
                        value={x.value}
                        onChange={(e) => changeWorkInfo(e.target.value, item, x)}
                      />
                    </Form.Item>
                  );
                })}
              </div>
              {item.child.map((x) => {
                if (x.label !== '工作概述') return;

                return (
                  <Form.Item key={x.field} wrapperCol={{ span: 24 }}>
                    <div className="pl-48px">
                      <CommonEdit html={x.value} setHtml={(e) => changeWorkInfo(e, item, x)} />
                    </div>
                  </Form.Item>
                );
              })}
              <Divider className="my-12px" />
            </div>
          ))}
          <Button
            type="primary"
            className="w-full"
            onClick={() => {
              setStoreWorkInfo((e) => {
                return [
                  ...e,
                  {
                    id: e.length + 1,
                    child: [
                      {
                        field: `companyName${e.length + 1}`,
                        label: '公司名称',
                        value: '字节跳动',
                      },
                      {
                        field: `postName${e.length + 1}`,
                        label: '岗位名称',
                        value: '前端开发工程师',
                      },
                      {
                        field: `companyStartTime${e.length + 1}`,
                        label: '开始时间',
                        value: '2020',
                      },
                      {
                        field: `companyEndTime${e.length + 1}`,
                        label: '结束时间',
                        value: '2023',
                      },
                      {
                        field: `companyWork${e.length + 1}`,
                        label: '工作概述',
                        value: '<ul><li>工作概述</li></ul>',
                      },
                    ],
                  },
                ];
              });
            }}
          >
            添加工作经历+
          </Button>
        </>
      ),
    },
    {
      key: '6',
      label: '项目经历',
      children: (
        <>
          {storeObjectInfo.map((item) => (
            <div key={item.id}>
              <div className="grid grid-cols-2">
                {item.child.map((x) => {
                  if (x.label === '项目概述') return;

                  return (
                    <Form.Item key={x.field} label={x.label}>
                      <Input
                        placeholder={`请输入${x.label}`}
                        value={x.value}
                        onChange={(e) => changeObjectInfo(e.target.value, item, x)}
                      />
                    </Form.Item>
                  );
                })}
              </div>
              {item.child.map((x) => {
                if (x.label !== '项目概述') return;

                return (
                  <Form.Item key={x.field} wrapperCol={{ span: 24 }}>
                    <div className="pl-48px">
                      <CommonEdit html={x.value} setHtml={(e) => changeObjectInfo(e, item, x)} />
                    </div>
                  </Form.Item>
                );
              })}
              <Divider className="my-12px" />
            </div>
          ))}
          <Button
            type="primary"
            className="w-full"
            onClick={() => {
              setStoreObjectInfo((e) => {
                return [
                  ...e,
                  {
                    id: e.length + 1,
                    child: [
                      {
                        field: `companyName${e.length + 1}`,
                        label: '项目名称',
                        value: '抖音平台',
                      },
                      {
                        field: `postName${e.length + 1}`,
                        label: '项目角色',
                        value: 'Web开发',
                      },
                      {
                        field: `companyStartTime${e.length + 1}`,
                        label: '开始时间',
                        value: '2020',
                      },
                      {
                        field: `companyEndTime${e.length + 1}`,
                        label: '结束时间',
                        value: '2023',
                      },
                      {
                        field: `companyWork${e.length + 1}`,
                        label: '项目概述',
                        value: '<ul><li>项目概述</li></ul>',
                      },
                    ],
                  },
                ];
              });
            }}
          >
            添加项目经历+
          </Button>
        </>
      ),
    },
  ];

  return (
    <div className="w-full py-24px pl-24px">
      <Title className="text-center" level={4}>
        编辑
      </Title>

      <Form {...layout}>
        <DragDropContext onDragEnd={onDragEnd}>
          <Droppable droppableId="droppable">
            {(provided) => (
              <div ref={provided.innerRef}>
                {storeOrder.map((item, index) => {
                  if (item.isNoShow) return;

                  return (
                    <Draggable key={item.key} draggableId={item.key} index={index}>
                      {(provided) => (
                        <div
                          ref={provided.innerRef}
                          {...provided.dragHandleProps}
                          {...provided.draggableProps}
                          className="mb-24px"
                        >
                          <div className="flex select-none items-center">
                            <Title level={5}>{item.label}</Title>
                            <div
                              className="mb-8px ml-12px cursor-pointer"
                              onClick={() => {
                                setStoreOrder((e) => {
                                  return e.map((x) => {
                                    if (x.key === item.key) {
                                      return {
                                        ...x,
                                        isOpen: !x.isOpen,
                                      };
                                    }

                                    return x;
                                  });
                                });
                              }}
                            >
                              {item.isOpen ? <RightOutlined /> : <DownOutlined />}
                            </div>
                            {/* 编辑名称 */}
                            {!item.showInput && !item.isNoChange && (
                              <div
                                title="编辑名称"
                                className="mb-8px ml-12px cursor-pointer"
                                onClick={() => {
                                  setStoreOrder((e) => {
                                    return e.map((x) => {
                                      if (x.key === item.key) {
                                        return {
                                          ...x,
                                          showInput: true,
                                        };
                                      }

                                      return x;
                                    });
                                  });
                                }}
                              >
                                <EditOutlined />
                              </div>
                            )}
                            {item.showInput && (
                              <Input
                                size="middle"
                                className="mb-8px w-200px"
                                onBlur={(val) => {
                                  setStoreOrder((e) => {
                                    return e.map((x) => {
                                      if (x.key === item.key) {
                                        return {
                                          ...x,
                                          label: val.target.value,
                                          showInput: false,
                                        };
                                      }

                                      return x;
                                    });
                                  });
                                }}
                                onPressEnter={(val) => {
                                  setStoreOrder((e) => {
                                    return e.map((x) => {
                                      if (x.key === item.key) {
                                        return {
                                          ...x,
                                          label: val.target.value,
                                          showInput: false,
                                        };
                                      }

                                      return x;
                                    });
                                  });
                                }}
                              />
                            )}
                            {/* 移除 */}
                            {item.isEdit && (
                              <Popconfirm
                                title="移除"
                                description="是否移除?"
                                onConfirm={() => {
                                  setStoreOrder((e) => {
                                    return e.map((x) => {
                                      if (x.key === item.key) {
                                        return {
                                          ...x,
                                          isNoShow: true,
                                        };
                                      }

                                      return x;
                                    });
                                  });
                                }}
                                okText="确定"
                                cancelText="取消"
                              >
                                <div title="移除" className="mb-8px ml-12px cursor-pointer">
                                  <DeleteOutlined />
                                </div>
                              </Popconfirm>
                            )}
                          </div>
                          <Divider className="my-12px" />
                          {!item.isOpen && allValues.find((x) => x.key === item.key).children}
                        </div>
                      )}
                    </Draggable>
                  );
                })}
                {provided.placeholder}
              </div>
            )}
          </Droppable>
        </DragDropContext>
      </Form>

      <Popconfirm title="重置表单" description="是否重置表单?" onConfirm={retAllData} okText="确定" cancelText="取消">
        <Button className="my-24px w-full" type="primary" danger>
          重置表单
        </Button>
      </Popconfirm>
    </div>
  );
};

export default ResumeCreate;
